<template>
    <div class="upload-book-div">
        <el-row type="flex" justify="center">
            <el-col :span="18">
                <!--书籍封面行-->
                <el-row class="cover-row" type="flex" justify="center">
                    <el-col :span="18">
                        <el-upload
                                class="upload-demo"
                                drag
                                action="https://jsonplaceholder.typicode.com/posts/"
                                multiple>
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将书籍图片拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>
                    </el-col>
                </el-row>
                <!--上传书籍表单-->
                <el-form :label-position="labelPosition" label-width="70px" status-icon ref="uploadBookForm" :model="uploadBookForm" :rules="rules">
                    <el-form-item label="书名" prop="bookName">
                        <el-input v-model.trim="uploadBookForm.bookName" size="small"></el-input>
                    </el-form-item>
                    <el-row :gutter="0">
                        <el-col :span="12">
                            <el-form-item label="作者" prop="author">
                                <el-input v-model.trim="uploadBookForm.author" size="small"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="出版社" prop="publishingHouse">
                                <el-input v-model.trim="uploadBookForm.publishingHouse" size="small"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="10">
                        <el-col :span="10">
                            <el-form-item label="价格" prop="price">
                                <el-input-number v-model.number="uploadBookForm.price" controls-position="right" :precision="2" :step="0.1" :min="0" :max="100000" size="mini"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="原价" prop="originalPrice">
                                <el-input-number v-model.number="uploadBookForm.originalPrice" controls-position="right" :precision="2" :step="0.1" :min="0" :max="100000" size="mini"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                        </el-col>
                    </el-row>
                    <el-form-item label="库存" prop="stock">
                        <el-input-number v-model.number="uploadBookForm.stock" controls-position="right" :min="1" :max="100" label="库存量" size="mini"></el-input-number>
                    </el-form-item>
                    <el-form-item label="选择标签" prop="type">
                        <el-checkbox-group v-show="false" v-model="uploadBookForm.type">
                            <el-checkbox v-for="(type, index) in bookType" :key="index" :label="type.typeValue" :name="type.typeName"></el-checkbox>
                        </el-checkbox-group>
                        <el-tag @close="handleCloseTag(tag)" v-for="tag in bookTypeTag" :key="tag.typeName" closable size="small">{{tag.typeValue}}</el-tag>
                        <el-button @click="addTag" title="点击添加标签" class="add-tag-btn" icon="el-icon-plus" size="mini" circle></el-button>
                    </el-form-item>
                    <el-form-item label="简介" prop="content">
                        <el-input type="textarea" v-model.trim="uploadBookForm.content" maxlength="255" show-word-limit :autosize="{ minRows: 2, maxRows: 3}"></el-input>
                    </el-form-item>
                    <el-form-item label="卖家的话" prop="remark">
                        <el-input type="textarea" v-model.trim="uploadBookForm.remark" maxlength="255" show-word-limit :autosize="{ minRows: 2, maxRows: 3}"></el-input>
                    </el-form-item>
                    <el-form-item label="封面链接" v-show="false">
                        <el-input v-model.trim="uploadBookForm.coverPicUrl" size="small"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button v-if="!isEdit" class="upload-btn" type="primary" :disabled="isDisabled" @click="onSubmit('uploadBookForm')" size="small">发布书籍信息</el-button>
                        <el-button v-if="isEdit" class="upload-btn" type="primary" :disabled="isDisabled" @click="onSubmit('uploadBookForm')" size="small">确认修改</el-button>
                        <el-button type="danger" @click="resetForm('uploadBookForm')" size="small">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <el-dialog title="请添加书籍标签" :visible.sync="dialogFormVisible" width="35%">
            <p style="margin-top: -10px;">频道（请优先选择频道）</p>
            <el-form label-position="top" :model="uploadBookForm">
                <el-form-item>
                    <!--<el-checkbox-group v-model="uploadBookForm.type">
                        <el-checkbox v-for="(type, index) in bookType" :key="index" :label="type.typeValue" :name="type.typeName"></el-checkbox>
                    </el-checkbox-group>-->
                    <el-checkbox-group v-model="uploadBookForm.parentType" @change="changeSecondType()" style="border-bottom: 1px solid #f0f0f0">
                        <el-checkbox v-for="(parentType, index) in firstType"  :key="index" :label="parentType.typeValue" :name="parentType.typeName"></el-checkbox>
                    </el-checkbox-group>
                    <el-checkbox-group v-model="uploadBookForm.type">
                        <el-checkbox v-for="(type, index) in secondTypeTemp" :key="index" :label="type.typeValue" :name="type.typeName"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelDialog">取 消</el-button>
                <el-button type="primary" @click="confirm">确 定</el-button>
            </div>
        </el-dialog>
<!--        <el-button @click="bookType.splice(0, 1)">dianjiawo</el-button>-->
        {{handleBookType}}
    </div>
</template>

<script>
    import storage from '../../model/storage.js';
    export default {
        name: "UploadBookPart",
        data(){
            return {
                labelPosition: 'right',
                isDisabled: false,
                dialogFormVisible: false,
                uploadBookForm: {
                    userInfoId: 0,
                    bookName: '',
                    author: '',
                    content: '',
                    price: 0,
                    originalPrice: 0,
                    coverPicUrl: 'https://images-na.ssl-images-amazon.com/images/I/51sDzGa%2BpfL.__BG0,0,0,0_FMpng_AC_UL240_SR240,240_.jpg',
                    stock: 0,
                    type: [],
                    parentType: [],
                    publishingHouse: '',
                    remark: ''
                },
                rules: {
                    bookName: [
                        { required: true, message: '书名不能为空', trigger: 'blur' },
                        { min: 1, max: 50, message: '书名长度应在1-50位之间'}
                    ],
                    author: [
                        { required: true, message: '作者不能为空', trigger: 'blur' },
                        { min: 1, max: 50, message: '作者名字长度应在1-50位之间'}
                    ],
                    price: [
                        { required: true, message: '价格不能为空', trigger: 'blur' }
                    ],
                    originalPrice: [
                        { required: true, message: '原价不能为空', trigger: 'blur' }
                    ],
                    stock: [
                        { required: true, message: '库存不能为空', trigger: 'blur' },
                        { type: 'number', message: '库存必须为数字值'}
                    ]
                },
                bookType: [

                ],
                bookTypeTag: [],
                bookTypeTagTemp: [],
                typeTemp: [],
                firstType:[],
                secondType:[],
                secondTypeTemp: []
            }
        },
        methods:{
            handleAvatarSuccess(res, file) {
                this.uploadBookForm.coverPicUrl = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            //提交表单
            onSubmit(formName){
                if(this.uploadBookForm.type.length === 0){
                    this.$message.warning("请至少选择一个标签。");
                    return false;
                }else if(this.uploadBookForm.type.length > 6){
                    this.$message.warning("最多只能选择6个标签。");
                    return false;
                }
                //处理标签数据
                var formTemp = JSON.parse(JSON.stringify(this.uploadBookForm));
                var url = '/manager/uploadBook';
                if (formTemp.type.length > 0) {
                    formTemp.type = formTemp.type.join(',');
                }else{
                    formTemp.type = '';
                }
                if (formTemp.parentType.length > 0){
                    formTemp.parentType = formTemp.parentType.join(',');
                } else{
                    formTemp.parentType = '';
                }
                console.log(formTemp);
                //添加用户id
                if (!(this.$route.name === 'editUploadedBook')) {
                    formTemp.userInfoId = this.$store.state.userInfo.userInfoId;
                }else{
                    url = '/manager/updateUploadedBook';
                }
                this.$refs[formName].validate((valid) => {
                    if(valid){
                        this.isDisabled = true;
                        this.$axios.post(
                            url,
                            formTemp
                        ).then(response => {
                            if(response.data.success){
                                //console.log(response.data.data);
                                if (this.$route.name === 'editUploadedBook') {
                                    this.$message.success("修改成功");
                                    this.$router.replace('/myCenter/uploadedBook');
                                }else{
                                    this.$message.success("发布成功");
                                    //this.resetForm('uploadBookForm');
                                }
                            }else{
                                console.log(response.data.msg);
                                if (response.data.msg === 'sessionInvalid') {
                                    sessionStorage.clear();
                                    this.$store.commit('updateIsLogin', false);
                                    this.$store.commit('updateUserInfo', null);
                                    this.$router.push({name: 'login'});
                                }
                            }
                        }).catch(error => {
                            console.log(error);
                        }).finally(() => {
                            this.isDisabled = false;
                        });
                    }else{
                        console.log("upload submit error");
                        return false;
                    }
                });
            },
            //重置按钮
            resetForm(formName){
                //console.log(this.$refs[formName]);
                this.$refs[formName].resetFields();
            },
            handleUploadedBookInfo(uploadedBookInfo) {
                uploadedBookInfo.type = uploadedBookInfo.type.split(',');
                uploadedBookInfo.parentType = uploadedBookInfo.parentType.split(',');
                Object.assign(this.uploadBookForm, uploadedBookInfo);
            },
            handleCloseTag(tag){
                this.uploadBookForm.type.splice(this.uploadBookForm.type.indexOf(tag.typeValue), 1);
                //this.bookTypeTag.splice(this.bookTypeTag.indexOf(tag), 1);
                //this.uploadBookForm.type.splice(this.uploadBookForm.type.indexOf(tag.value), 1);
            },
            //添加类别标签
            addTag(){
                //备份上传表单中的书籍标签
                this.typeTemp = JSON.parse(JSON.stringify(this.uploadBookForm.type));
                //备份bookTypeTag
                this.bookTypeTagTemp =JSON.parse(JSON.stringify(this.bookTypeTag));
                this.dialogFormVisible = true;
            },
            //当取消时
            cancelDialog(){
                this.uploadBookForm.type = this.typeTemp;
                this.dialogFormVisible = false;
            },
            //当点击确定时
            confirm(){
                this.dialogFormVisible = false;
            },
            getBookType(){
                this.$axios.get('/getBookType')
                    .then(response => {
                        if(response.data.success){
                            this.bookType = response.data.data;
                            //取得的标签进行分类
                            this.getSecondBookType(response.data.data);
                        }else{
                            if(response.data.msg === 'sessionInvalid'){
                                storage.isSessionValid(this);
                            }
                        }
                }).catch(error => {
                    console.log(error);
                }).finally(() => {

                })
            },
            getSecondBookType(data){
                for (let i = 0 ; i<data.length ; i++ ) {
                    //一级标签
                    if (data[i].typeLevel === 1){
                        this.firstType.push(JSON.parse(JSON.stringify(data[i])));
                    }
                    //二级标签
                    if (data[i].typeLevel === 2){
                        this.secondType.push(JSON.parse(JSON.stringify(data[i])));
                    }
                }
                //获取二级标签内容（编辑时）
                this.changeSecondType();
            },
            changeSecondType(){
                var typeName = '';
                this.secondTypeTemp = [];
                if (this.uploadBookForm.parentType.length > 0){
                    //循环频道
                    for (var i = 0 ; i < this.uploadBookForm.parentType.length; i++){
                        console.log(this.firstType.length);
                        console.log(this.secondType.length);
                        //找到频道对应的typeName
                        for (var x = 0; x<this.firstType.length; x++){
                            if (this.firstType[x].typeValue === this.uploadBookForm.parentType[i]) {
                                typeName = this.firstType[x].typeName;
                            }
                        }
                        //找到二级标签对于的parentType
                        for (var j =0 ; j < this.secondType.length; j++){
                            if (this.secondType[j].parentType === typeName){
                                this.secondTypeTemp.push(JSON.parse(JSON.stringify(this.secondType[j])));
                            }
                        }
                        console.log(typeName);
                        console.log(this.secondTypeTemp);
                    }
                } else{
                    this.secondTypeTemp = [];
                }
            }
        },
        computed: {
            isEdit(){
                return this.$route.name === 'editUploadedBook';
            },
            //实时监控bookType
            handleBookType(){
                this.bookTypeTag = [];
                if(this.bookType.length > 0){
                    for(var i = 0 ; i < this.uploadBookForm.type.length ; i++){
                        var j = 0;
                        for( ; j < this.bookType.length ; j ++){
                            if (this.bookType[j].typeValue === this.uploadBookForm.type[i]) {
                                this.bookTypeTag.push(JSON.parse(JSON.stringify(this.bookType[j])));
                                break;
                            }
                        }
                        //若所有标签中没有已选中的标签，则将该标签从已选中的标签中剔除
                        if(j === this.bookType.length){
                            this.uploadBookForm.type.splice(i, 1);
                            i--;
                        }
                    }
                }
                return '';
            }
        },
        mounted() {
            //若跳转到修改上传书籍信息组件
            if (this.$route.name === 'editUploadedBook') {
                this.handleUploadedBookInfo(this.$route.params.uploadedBook);
            }
            //挂载时请求服务器获取书签数据
            this.getBookType();
        }
    }
</script>

<style scoped>

    .cover-row{
        margin: 20px 0;
    }

    .upload-btn{
        margin-left: 30%;
        transform: translateX(-50%);
    }

    .el-tag + .el-tag {
        margin-left: 10px;
    }

    .add-tag-btn{
        margin-left: 10px;
    }

</style>